// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    try {
        const wxContext = cloud.getWXContext()

        const {
            account,
            password
        } = event

        // 用户数据
        let data = {
            _openid: wxContext.OPENID,
            account,
            password,
            phone: "",
            createTime: Date.now(),
            avatar: "",
            merchantName: "",
            organizationCode: "",
            legalPerson: "",
            address: "",
            wxId: "",
            birthday: "",
            birthdayValue: 0,
        }

        // 查询是否有相同账号
        const result = await db.collection('user').where({
            account,
        }).get()

        if (result.data.length > 0) {
            // 直接登录
            return {
                code: 401,
                msg: "已有相同账号，请重新输入",
            }
        }

        // 获取总数
        const countResult = await db.collection('user').count()

        // 注册
        data = {
            ...data,
            userId: countResult.total + 1,
        }
        const res = await db.collection('user').add({
            data
        })
        // 返回最新数据
        // const result = await db.collection('user').where({
        //     _openid: wxContext.OPENID,
        //     account,
        //     password,
        // }).get()

        if (res.errMsg = "collection.add:ok") {
            return {
                code: 200,
                // data: result.data[0],
                msg: "注册成功",
            }
        } else {
            return {
                code: 401,
                msg: "注册失败",
            }
        }
    } catch {
        return {
            code: 500,
            msg: "注册失败",
        }
    }
}